﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection.Emit;
using System.Reflection;

namespace AutoWrapper
{
    public static class MethodServiceAttributeDecorators
    {
        public static void DecorateMethod(TypeBuilder tb, MethodInfo mi)
        {
            string methodName = mi.Name;

            ParameterInfo[] parameterInfos = mi.GetParameters();
            Type[] parametersTypes = new Type[parameterInfos.Length];
            for (int i = 0; i < parameterInfos.Length; i++)
            {
                parametersTypes[i] = parameterInfos[i].ParameterType;
            }
            MethodBuilder myMethodBuilder = tb.DefineMethod(methodName, MethodAttributes.Public | MethodAttributes.Virtual
                ,mi.CallingConvention, mi.ReturnType, parametersTypes);
            // Get an ILGenerator and emit a body for the dynamic method.


            for (int i = 0; i < parameterInfos.Length; i++)
            {
                myMethodBuilder.DefineParameter(i+1, ParameterAttributes.None, parameterInfos[i].Name);
            }
            // the operation contract attribute
            myMethodBuilder.SetCustomAttribute(ServiceAttributeBuilders.OperationContractAttributeBuilder());
            
            // if the parameters are all basic types, then we should bind the WebGet attribute to it.
            // the WebGet attribute
            // the 
            ILGenerator il = myMethodBuilder.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0);
            for (int parameterIndex = 1; parameterIndex < parameterInfos.Length; ++parameterIndex)
            {
                il.Emit(OpCodes.Ldarg, parameterIndex);
            }

            il.Emit(OpCodes.Ldarg_0);
            il.EmitCall(OpCodes.Call, mi, null);
            il.Emit(OpCodes.Ret);

                    
        }
    }
}
